package com.ruoyi.framework.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * Mybatis Plus 配置
 *
 * @author ruoyi
 */
@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        return interceptor;
    }

    /**
     * 自定义公共字段自动注入
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new CustomMetaObjectHandler();
    }

    /**
     * map返回查询结果时，自动转驼峰
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return i -> i.setObjectWrapperFactory(new MybatisMapWrapperFactory());
    }

    // 分页优化
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 设置数据库类型为mysql
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInnerInterceptor.setMaxLimit(-1L);
        // 翻页溢出处理
        paginationInnerInterceptor.setOverflow(true);
        return paginationInnerInterceptor;
    }


    /**
     * 自定义sql字段填充器，自动填充创建修改相关字段
     */
    private static class CustomMetaObjectHandler implements MetaObjectHandler {

        private static final String CREATE_USER = "createUser";

        private static final String CREATE_TIME = "createTime";

        private static final String UPDATE_USER = "updateUser";

        private static final String UPDATE_TIME = "updateTime";

        /**
         * 新增模块时，需要添加的字段
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            Long userUniqueId = this.getUserUniqueId();
            Date date = new Date();

            if (ObjectUtil.isNotEmpty(metaObject.hasSetter(CREATE_USER))) {
                setFieldValByName(CREATE_USER, userUniqueId, metaObject);
            }
            if (ObjectUtil.isNotEmpty(metaObject.hasSetter(CREATE_TIME))) {
                setFieldValByName(CREATE_TIME, date, metaObject);
            }
            if (ObjectUtil.isNotEmpty(metaObject.hasSetter(UPDATE_USER))) {
                setFieldValByName(UPDATE_USER, userUniqueId, metaObject);
            }
            if (ObjectUtil.isNotEmpty(metaObject.hasSetter(UPDATE_TIME))) {
                setFieldValByName(UPDATE_TIME, date, metaObject);
            }
        }

        /**
         * 编辑模块时，需要添加的字段
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            if (ObjectUtil.isNotEmpty(metaObject.hasSetter(UPDATE_USER))) {
                setFieldValByName(UPDATE_USER, this.getUserUniqueId(), metaObject);
            }
            if (ObjectUtil.isNotEmpty(metaObject.hasSetter(UPDATE_TIME))) {
                setFieldValByName(UPDATE_TIME, new Date(), metaObject);
            }
        }

        /**
         * 获取用户id
         */
        private Long getUserUniqueId() {
            try {
                return SecurityUtils.getUserId();
            } catch (Exception e) {
                return -1L;
            }
        }

    }

}